package aof.controller;

import android.app.Dialog;
import android.content.Context;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Intent;

import java.util.ArrayList;
import aof.helper.DateTimeHelper;
import aof.helper.MyDBHelper;
import aof.model.M_COSTDAY;
import aof.biz.M_COSTDAY_BIZ;

public class MainController extends Activity {

    ArrayList<M_COSTDAY> Myitems;
    ViewAdapter MyviewAdpter;
    int start = 0;
    int limit = 20;
    private int statusView;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

        findViewById(R.id.layoutYearMonthMain).setVisibility(View.GONE);
        //create an ArrayAdaptar from the String Array
        final ListView lisView1 = (ListView) findViewById(R.id.listView1);
        Myitems = new M_COSTDAY_BIZ(MainController.this).GetAll(limit,start);
        MyviewAdpter = new ViewAdapter(this, R.layout.viewitem, Myitems);
        lisView1.setAdapter(MyviewAdpter);
        lisView1.setTextFilterEnabled(true);
        lisView1.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                statusView = scrollState;
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (statusView > 0) {
                    ListAdapter adapter = view.getAdapter();
                    TextView Holder = (TextView)view.findViewById(R.id.txtDate);
                    TextView txtMonth = (TextView) findViewById(R.id.txtMonthMain);
                    TextView txtYear = (TextView) findViewById(R.id.txtYearMain);
                    txtMonth.setText(Holder.getTag().toString().split(",")[0]);
                    txtYear.setText(Holder.getTag().toString().split(",")[1]);

                    if (firstVisibleItem == 0) {
                        view.findViewById(R.id.layoutYearMonth).setVisibility(View.GONE);
                    }
                    boolean loadMore =  firstVisibleItem + visibleItemCount >= totalItemCount-1;
                    if(loadMore){
                        if (adapter instanceof ViewAdapter) {
                            ViewAdapter vad = (ViewAdapter)adapter;
                            M_COSTDAY costday = (M_COSTDAY)adapter.getItem(totalItemCount-1);
                            ArrayList<M_COSTDAY> data = new M_COSTDAY_BIZ(MainController.this).GetAll(10,costday.getROWNUM());
                            if(data != null && data.size() > 0){
                                for(M_COSTDAY _data : data){
                                    Myitems.add(_data);
                                    vad.add(_data);
                                }
                                vad.notifyDataSetChanged();
                            }
                        }
                    }

                }
            }
        });

        final ImageButton btnFind = (ImageButton) findViewById(R.id.btnFind);
        btnFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        final ImageButton btnAdd = (ImageButton) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent newActivity = new Intent(getApplicationContext(), AddCostController.class);
                startActivity(newActivity);
                overridePendingTransition(R.anim.left_to_right_enter, R.anim.left_to_right_leave);
            }
        });

        final ImageButton btnDelete = (ImageButton) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final MyDBHelper db = new MyDBHelper(MainController.this);
                db.resetDataBase();
            }
        });
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main_controller, menu);
		return true;
	}
    @Override
    public void onBackPressed() {
        Log.d("CDA", "onBackPressed Called");

        final Dialog dialog = new Dialog(getApplicationContext(),R.style.DialogSlideAnim);
        dialog.setContentView(R.layout.dialogtype);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER_VERTICAL;
        wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        window.setAttributes(wlp);
        dialog.setCancelable(true);

        TextView txtview = (TextView)dialog.findViewById(R.id.dialog_text);
        txtview.setText("Exits Program ?");

        Button btnok = (Button)dialog.findViewById(R.id.btnDialogOk);
        btnok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        Button btncencel = (Button)dialog.findViewById(R.id.btnDialogCencel);
        btncencel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }
    public class ViewAdapter extends ArrayAdapter<M_COSTDAY> {

        private Context context;
        private ArrayList<M_COSTDAY> Myitems;

        public ViewAdapter(Context context, int textViewResourceId, ArrayList<M_COSTDAY> items) {
            super(context, textViewResourceId, items);
            this.context = context;
            this.Myitems = new ArrayList<M_COSTDAY>();
            this.Myitems.addAll(items);
        }
        class ViewHolderCost {
             LinearLayout layoutYearMonth;
             TextView txtDay;
             TextView txtMonth;
             TextView txtYear;
             TextView txtTotal;
             TextView txtImcome;
             TextView txtExpenditure;
             TextView txtBalace;
        }
        public void add(M_COSTDAY item){
            this.Myitems.add(item);
        }
        public void addAll(ArrayList<M_COSTDAY> item){
            this.Myitems.addAll(item);
        }

        @Override
        public View getView(final int position, View convertView,ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            ViewHolderCost holder = null;

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.viewitem, null);
                holder = new ViewHolderCost();
                holder.layoutYearMonth = (LinearLayout) convertView.findViewById(R.id.layoutYearMonth);
                holder.txtDay = (TextView) convertView.findViewById(R.id.txtDate);
                holder.txtMonth = (TextView) convertView.findViewById(R.id.txtMonth);
                holder.txtYear = (TextView) convertView.findViewById(R.id.txtYear);
                holder.txtTotal = (TextView) convertView.findViewById(R.id.txtCostTotal);
                holder.txtImcome = (TextView) convertView.findViewById(R.id.txtCostIncome);
                holder.txtExpenditure = (TextView) convertView.findViewById(R.id.txtCostExpenditure);
                holder.txtBalace = (TextView) convertView.findViewById(R.id.txtCostBalace);
                convertView.setTag(holder);

                if(position == 0){
                    findViewById(R.id.layoutYearMonthMain).setVisibility(View.VISIBLE);
                    ((TextView) findViewById(R.id.txtMonthMain)).setText(this.Myitems.get(position).getMONTH().toString());
                    ((TextView) findViewById(R.id.txtYearMain)).setText(this.Myitems.get(position).getYEAR().toString());
                }
            }
            else
            {
                holder = (ViewHolderCost)convertView.getTag();
            }

            if (this.Myitems.get(position).getROWNUM() > 1
                    && (DateTimeHelper.IsLastDayInMonth(this.Myitems.get(position).getDAY(),this.Myitems.get(position).getMONTH())
                    || this.Myitems.get(position).getROWNUM().equals(1))) {
                holder.layoutYearMonth.setVisibility(View.VISIBLE);
            } else {
                holder.layoutYearMonth.setVisibility(View.GONE);
            }

            holder.txtDay.setText(this.Myitems.get(position).getDAY().toString());
            holder.txtDay.setTag(this.Myitems.get(position).getMONTH().toString()+ "," + this.Myitems.get(position).getYEAR().toString());
            holder.txtMonth.setText(this.Myitems.get(position).getMONTH().toString());
            holder.txtYear.setText(this.Myitems.get(position).getYEAR().toString());
            holder.txtTotal.setText(this.Myitems.get(position).getTOTAL().toString());
            holder.txtImcome.setText(this.Myitems.get(position).getINCOME().toString());
            holder.txtExpenditure.setText(this.Myitems.get(position).getEXPENDITURE().toString());
            holder.txtBalace.setText(this.Myitems.get(position).getBALANCE().toString());
            if (this.Myitems.get(position).getMINUS().equals("1"))
                holder.txtBalace.setTextColor(getResources().getColor( R.color.costBalanceM));
            else
                holder.txtBalace.setTextColor(getResources().getColor(R.color.costBalance));

            return convertView;

        }

    }

}
